import Events from './index'
import Http from 'common/Http'
import Store from 'common/Store'
export default class Event2 extends Events {

  static _ins: Event2
  static get instance(): Event2 {
    return this._ins || new Event2;
  }
  constructor() {
    super();
    Event2._ins = this
  }

  /**
   * 活动键值
   */
  protected _eventIndex = 1

  /**
   * 当前期数 0,1,2
   */
  private _issue: number = null
  private _systemTicket = []
  private _userTicket = []

  get systemTicket(): number[][] {
    return this._systemTicket
  }
  infoInit(state: InfoState) {
    this.info = state
    this.setUserTicket(state.UserTicket)
    var systemTicket: object = state.SystemTicket
    var keys: string[] = Object.keys(systemTicket)
    if (keys.length) {
      keys.forEach(step => {
        this._systemTicket[Number(step)] = Array.from(systemTicket[step]).map(index => Number(index))
      })
      var issue = Number(keys.last) + 1
      this._issue = Math.min(issue, 2)
    } else {
      this._issue = 0
    }
    return this._issue
  }

  get userTicket(): number[][] {
    return this._userTicket
  }
  setUserTicket(userTicket: object) {
    var keys: string[] = Object.keys(userTicket)
    if (keys.length) {
      keys.forEach(step => {
        this._userTicket[Number(step)] = Array.from(userTicket[step]).map(index => Number(index))
      })
    }
  }

  get issue() {
    return this._issue
  }

  public gotRewardMap = {
    0: false,
    1: false,
    2: false
  }

  queryEvent(tag, params?) {
    var datas: any = {
      groupId: Events.groupId,
      actId: this.actId,
      token: Store.instance.map.userInfo.token
    }
    switch (tag) {
      case INFO:
        datas.rewardId = this.rewardId.last
        break;
      case JOIN:
        datas.step = params.step
        if (params.ticket) datas.ticket = params.ticket
        if (params.rewardId) datas.rewardId = params.rewardId
        break;
    }
    return Http.instance.getActivity(tag, datas).then(data => {
      var is200 = data.code === 200
      var is300 = data.code === 300

      if(is300) return data
      
      switch (tag) {
        case INFO:
          data.state.issue = is200 ? this.infoInit(data.state) : 0
          this.info = data.state
          break;
        case CDKEYS:
          if (is200) {
            this.history = data.state
            if (this.history.length) {
              this.history.forEach(item => {
                var issue = item.extInfo.step
                this.gotRewardMap[issue] = true
              });
            }
          } else {
            this.history = []
          }
      }
      return data
    })
  }

}
